package com.ztom.top100;

/**
 * 合并两个有序链表
 * <p>
 * https://leetcode-cn.com/problems/merge-two-sorted-lists/
 *
 * @author ZhangTao
 */
public class Code12MergeTwoLists {

    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        if (list1 == null) {
            return list2;
        }
        if (list2 == null) {
            return list1;
        }

        // 哨兵
        ListNode dummy = new ListNode(-1);
        // 当前节点
        ListNode node = dummy;
        ListNode i = list1;
        ListNode j = list2;
        while (i != null && j != null) {
            if (i.val <= j.val) {
                node.next = i;
                i = i.next;
            } else {
                node.next = j;
                j = j.next;
            }
            node = node.next;
        }
        while (i != null) {
            node.next = i;
            node = node.next;
            i = i.next;
        }
        while (j != null) {
            node.next = j;
            node = node.next;
            j = j.next;
        }
        return dummy.next;
    }

    /**
     * 递归实现, 会破坏原链表
     *
     * @param list1
     * @param list2
     * @return
     */
    public ListNode mergeTwoLists1(ListNode list1, ListNode list2) {
        if (list1 == null) {
            return list2;
        }
        if (list2 == null) {
            return list1;
        }
        if (list1.val < list2.val) {
            list1.next = mergeTwoLists1(list1.next, list2);
            return list1;
        } else {
            list2.next = mergeTwoLists1(list1, list2.next);
            return list2;
        }
    }
}
